﻿using System.Globalization;
using CsvHelper;

namespace AntBlazorTableSample.Api.Models
{
    public sealed class CustomerStore
    {
        private readonly IWebHostEnvironment _webEnv;
        private readonly Lazy<List<Customer>> _customers;

        public CustomerStore(IWebHostEnvironment webEnv)
        {
            _webEnv = webEnv;
            _customers = new Lazy<List<Customer>>(ReadCustomers);
        }

        public List<Customer> Customers => _customers.Value;

        private List<Customer> ReadCustomers()
        {
            using var streamReader = new StreamReader(Path.Combine(_webEnv.WebRootPath, "customers.csv"));
            using var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture);
            var records = csvReader.GetRecords<Customer>();
            return [..records];
        }
    }
}
